/*
 * Copyright © 2009 Gerald Isaac Schwarz
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package base;

import java.util.ArrayList;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Color;
import java.awt.Rectangle;
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import org.xml.sax.SAXException;

public class GameLoader {
	private File file;
	private Document document;
	private ArrayList<Player> players;
	private ArrayList<Piece> types;
	private Board board;
	private Engine engine;
	private Player currentPlayer;
	
	public GameLoader(File file) {
		this.file = file;
		
		if (!this.file.exists()) {
			throw new RuntimeException("Specified file doesn't exist.");
		}
		else if (this.file.isDirectory()) {
			throw new RuntimeException("Specified file is a directory.");
		}
		
		try {
			this.getDocument();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			this.loadGame();
		} catch (DOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void getDocument() throws IOException, SAXException, ParserConfigurationException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(true);
//		dbf.setNamespaceAware(true);
		dbf.setIgnoringElementContentWhitespace(true);
		this.document = dbf.newDocumentBuilder().parse(file);
		this.document.getDocumentElement().normalize();
	}
	
	private void loadTypes() {
		NodeList typeNodes = this.document.getElementsByTagName("type");
		this.types = new ArrayList<Piece>();
		
		for (int i = 0; i < typeNodes.getLength(); i++) {
			Element type = (Element) typeNodes.item(i);
			String name = this.getTextContent(type.getAttributes().getNamedItem("name"));
			
			String rule_type;
			
			if (type.hasAttribute("rule_type")) {
				rule_type = this.getTextContent(type.getAttributes().getNamedItem("rule_type"));
			}
			else {
				rule_type = null;
			}
			
			String representation = this.getTextContent(type.getAttributes().getNamedItem("representation"));
			NodeList moveNodes = type.getElementsByTagName("move");
			NodeList upgradeNodes = type.getElementsByTagName("upgrade");
			ArrayList<Move> moves = new ArrayList<Move>();
			ArrayList<String> upgrades= new ArrayList<String>();
			
			for (int h = 0; h < moveNodes.getLength(); h++) {
				Element move = (Element) moveNodes.item(h);
				int x = Integer.parseInt(this.getTextContent(move.getElementsByTagName("x").item(0)));
				int y = Integer.parseInt(this.getTextContent(move.getElementsByTagName("y").item(0)));
				int repetitions = Integer.parseInt(this.getTextContent(move.getElementsByTagName("repetitions").item(0)));
				boolean isMove = Boolean.parseBoolean(this.getTextContent(move.getElementsByTagName("is_move").item(0)));
				boolean isAttack = Boolean.parseBoolean(this.getTextContent(move.getElementsByTagName("is_attack").item(0)));
				
				moves.add(new Move(new Point(x, y), repetitions, isMove, isAttack));
			}
			
			for (int h = 0; h < upgradeNodes.getLength(); h++) {
				upgrades.add(this.getTextContent(upgradeNodes.item(h).getAttributes().getNamedItem("name")));
			}
			
			this.types.add(new Piece(name, rule_type, representation, moves, upgrades, null));
		}
	}
	
	private void loadPlayers() {
		NodeList players = this.document.getElementsByTagName("player");
		this.players = new ArrayList<Player>();
		
		for (int i = 0; i < players.getLength(); i++) {
			String name = this.getTextContent(players.item(i).getAttributes().getNamedItem("name"));
			int id = Integer.parseInt(this.getTextContent(players.item(i).getAttributes().getNamedItem("id")));
			int direction = Integer.parseInt(this.getTextContent(players.item(i).getAttributes().getNamedItem("direction")));
			String colorConstant = this.getTextContent(players.item(i).getAttributes().getNamedItem("color"));
			
			Color color;
			
			try {
				color = (Color) Color.class.getField(colorConstant).get(null);
			}
			catch (Exception e) {
				color = Color.BLACK;
			}
			
			this.players.add(new Player(name, id, color, direction));
		}
	}
	
	private void loadBoard() {
		Node boardNode = this.document.getElementsByTagName("board").item(0);
		
		int boardWidth = Integer.parseInt(this.getTextContent(boardNode.getAttributes().getNamedItem("width")));
		int boardHeight = Integer.parseInt(this.getTextContent(boardNode.getAttributes().getNamedItem("height")));
		Dimension boardSize = new Dimension(boardWidth, boardHeight);
		
		NodeList upgrade_zoneNodes = ((Element) boardNode).getElementsByTagName("upgrade_zone");
		ArrayList<UpgradeZone> upgradeZones = new ArrayList<UpgradeZone>();
		ArrayList<Piece> pieces = new ArrayList<Piece>();
		
		for (int h = 0; h < upgrade_zoneNodes.getLength(); h++) {
			int x = Integer.parseInt(this.getTextContent(upgrade_zoneNodes.item(h).getAttributes().getNamedItem("x")));
			int y = Integer.parseInt(this.getTextContent(upgrade_zoneNodes.item(h).getAttributes().getNamedItem("y")));
			int zoneWidth = Integer.parseInt(this.getTextContent(upgrade_zoneNodes.item(h).getAttributes().getNamedItem("width")));
			int zoneHeight = Integer.parseInt(this.getTextContent(upgrade_zoneNodes.item(h).getAttributes().getNamedItem("height")));
			
			NodeList idNodes = ((Element) upgrade_zoneNodes.item(h)).getElementsByTagName("id");
			ArrayList<Player> players = new ArrayList<Player>();
			
			for (int q = 0; q < idNodes.getLength(); q++) {
				players.add(this.players.get(Integer.parseInt(this.getTextContent(idNodes.item(q)))));
			}
			
			upgradeZones.add(new UpgradeZone(new Rectangle(x, y, zoneWidth, zoneHeight), players));
		}
		
		NodeList pieceNodes = ((Element) boardNode).getElementsByTagName("piece");
		
		for (int h = 0; h < pieceNodes.getLength(); h++) {
			String type = this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("type"));
			Integer id = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("player")));
			boolean is_alive = Boolean.parseBoolean(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("is_alive")));
			int x = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("x")));
			int y = Integer.parseInt(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("y")));
			
			Piece upgrade = null;
			Player player = this.players.get(id);
			
			if (((Element) pieceNodes.item(h)).hasAttribute("upgrade")) {
				upgrade = this.getPieceByType(this.getTextContent(pieceNodes.item(h).getAttributes().getNamedItem("upgrade")));
			}
			
			Piece template = this.getPieceByType(type);
			State initialState;
			
			if (template != null) {
				Piece piece = new Piece(template);
				
				if (upgrade != null) {
					initialState = new State(piece, new Point(x, y), is_alive, player, upgrade);
				}
				else {
					initialState = new State(piece, new Point(x, y), is_alive, player, piece);
				}
				
				piece.setInitialState(initialState);
				
				pieces.add(piece);
			}
			
		}
		
		this.board = new RealBoard(boardSize, pieces, upgradeZones);
	}
	
	/**
	 * 
	 * @param type The type of the piece type we want to get an instance of.
	 * @return New instance of a piece from the piece templates.
	 */
	
	private Piece getPieceByType(String type) {
		for (Piece template : this.types) {
			if (template.getType().equals(type)) {
				return new Piece(template);
			}
		}
		
		return null;
	}
	
	private void loadGame() throws DOMException, InstantiationException, IllegalAccessException, ClassNotFoundException {
		this.loadTypes();
		this.loadPlayers();
		this.loadCurrentPlayer();
		this.loadBoard();
		this.loadEngine();
	}
	
	private void loadCurrentPlayer() {
		int index = Integer.parseInt(this.getTextContent(this.document.getElementsByTagName("current_player").item(0)));
		
		this.currentPlayer = this.players.get(index);
	}
	
	private void loadEngine() {
		this.board.setCurrentPlayer(this.currentPlayer);
		this.setEngine(new Engine(this.board, this.types));
	}
	
	private String getTextContent(Node node) {
		return node.getTextContent().trim();
	}

	private void setEngine(Engine engine) {
		this.engine = engine;
	}

	public Engine getEngine() {
		return this.engine;
	}
}
